package com.geekstudy.week3.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", filterName = "week3DemoFilter")
public class Week3DemoFilter implements Filter {

    final Logger logger = LoggerFactory.getLogger(Week3DemoFilter.class);

    final String WEEK3 = "week3";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        logger.info("doFilter");
        String week3Attribute = (String)request.getAttribute(WEEK3);
        if(week3Attribute == null || week3Attribute.isEmpty()) {
            String value = "demoWeek3";
            request.setAttribute(WEEK3, value);
            logger.info("doFilter set request attribute {}={} ", WEEK3, value);
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        logger.info("destroy");
    }
}
